/* axios请求封装 */
import axios from 'axios';
import qs from 'qs';
import Mint from 'mint-ui';
import Cookie from '../local-cookie';
import router from '../../../router/pc/index';
import api from './api';
// import vm from 'vm';

const CancelToken = axios.CancelToken;
const errorHandle = (err) => {
	const errStatus = (err.response && err.response.status) || (err.data && err.data.errcode);
	if (errStatus) {
		switch (errStatus) {
			case 451:
				Message.error('token过期，请重新登录');
				router.push({
					name: 'Login',
				});
				break;
			case 404:
				vm_l.$messagebox({
					title: '提示',
					message: '404: 网络请求不存在',
					showCancelButton: false,
					confirmButtonText: "确认"
				})
				break;
			case 500:
				if (err.response.data && err.response.data.code && err.response.data.code == '911') {
					const params = {
						grant_type: 'refresh_token',
						client_id: 'house',
						client_secret: 'house',
						refresh_token: Cookie.get('refresh_token'),
					};
					vm_l.$messagebox({
						title: '提示',
						message: err.response.data.msg,
						showCancelButton: false,
						confirmButtonText: "确认"
					})
				} else if (err.response.data && err.response.data.code && err.response.data.code == '710') {
					vm_l.$messagebox({
						title: '提示',
						message: err.response.data.msg,
						showCancelButton: false,
						confirmButtonText: "确认"
					})

				} else {
					const resMsg = err.response.data && err.response.data.msg;
					const message = resMsg ? `(${resMsg})` : '';
					vm_l.$messagebox({
						title: '提示',
						message:message==null||message==''||message==undefined?"请求报错":message ,
						showCancelButton: false,
						confirmButtonText: "确认"
					})
				}
				break;
			default:
				vm_l.$messagebox({
					title: '提示',
					message: err.response.data.message,
					showCancelButton: false,
					confirmButtonText: "确认"
				})
		}
	} else if (err.toString().indexOf('timeout') != -1) {
		vm_l.$messagebox({
			title: '提示',
			message: '请求超时',
			showCancelButton: false,
			confirmButtonText: "确认"
		})

	}
};
let cancelRequest;

const ajax = axios.create({
	timeout: 15000,
});
let vm_l;
ajax.interceptors.request.use(
	(config) => {
		// 如果是登陆或注册请求就用x-www-form-urlencoded   /report/status
		if (config.url.indexOf('/report/status') >= 0||config.url.indexOf('/service-payment/scrt/business/report') >= 0||config.url.indexOf('/busi/cata') >= 0||config.url.indexOf('check/request')>=0||config.url.indexOf('check/status')>=0) {
			config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
		} else {
			config.headers['Content-Type'] = 'application/json;charset=UTF-8';
		}
		return config;
	},
	err => Promise.error(err),
);

ajax.interceptors.response.use(
	(res) => {
		if (res.status === 200) {
			return Promise.resolve(res);
		}
		return Promise.reject(res);
	},
	(err) => {
		return Promise.reject(err.response);
		errorHandle(err);
	},
);

/**
 * 主要的请求方法封装
 * @param { String }  method  [请求方法，默认为‘get’]
 * @param { Object }  vm  [实例对象]
 * @param { String }  url [api接口]
 * @param { Object }  params  [请求参数]
 * @param { Function }  callback  [回调函数]
 */
const request = (method, vm, url, params, callback, hideLoading) => {
	vm_l=vm;
	if (!url || typeof url != 'string') {
		throw new Error('接口URL不正确！');
	}
	if (!params || typeof params == 'string') {
		params = {};
	}

	let config = {
		method,
		url,
		cancelToken: new CancelToken((c) => {
			cancelRequest = c;
		}),
	};

	if (method === 'get') {
		config = Object.assign(config, {
			params
		});
	} else if (url.indexOf('/report/status') >= 0 ||url.indexOf('/check/request') >= 0 || url.indexOf('/business/report') >= 0 || url.indexOf('busi/cata') >= 0) {
		config = Object.assign(config, {
			data: qs.stringify(params),
			method: 'post'
		});
	} else {
		config = Object.assign(config, {
			data: params
		});
	}
	if (!hideLoading) {
		vm.$indicator.open({
			text: '加载中...',
			spinnerType: 'fading-circle'
		});
	}

	return new Promise((resolve) => {
		ajax(config)
			.then((res) => {
				if (res && res.data && res.data.errcode) {
					errorHandle(res);
					return;
				}
				resolve(res);
				if (typeof callback === 'function') {
					callback.call(vm, res.data);
				}
				if (!hideLoading) {
					vm.$indicator.close();
				}
			}).catch((err) => {
				callback.call(vm, err.data);			
				resolve(err);
				if (!hideLoading) {
					vm.$indicator.close();
				}
			});
	});
}

export default {
	/**
	 * 取消请求的方法，在页面中需要的地方this.$ajax.cancel()调用即可
	 * @param  { String }  txt  [控制台显示的Cancel-Message]
	 */
	cancel(txt) {
		if (typeof(cancelRequest) === 'function') {
			vm.$indicator.close();
			return cancelRequest(txt);
		}
	},
	get(args) {
		return request('get', ...args);
	},
	post(args) {
		return request('post', ...args);
	},
	put(args) {
		return request('put', ...args);
	},
	delete(args) {
		return request('delete', ...args);
	},
	login(args) {
		return request('login', ...args);
	},
	/**
	 * 同步请求方法
	 * @param { Array } functions [传入的请求方法数组（必须是ajax请求的方法）]
	 */
	all(functions) {
		return Promise.all(functions);
	}
};
